import { LoginService } from "./login.service";
import { ApiTags } from "@nestjs/swagger";
import { ReqLoginDto } from "./dto/req-login.dto";
import { Body, Controller, Get, Post, Req, UseGuards, Headers } from "@nestjs/common";
import { LocalAuthGuard } from "src/common/guards/local-auth.guard";
import { Request } from "express";
import { ResLoginDto } from "./dto/res-login.dto";
import { User, UserEnum } from "src/common/decorators/user.decorator";
import { Public } from "src/common/decorators/public.decorator";
import { DataObj } from "src/common/class/data-obj.class";

@ApiTags("登录")
@Controller()
export class LoginController {
  constructor(private readonly loginService: LoginService) {}

  /**
   * @description: 用户登录
   * @return {*}
   */
  @Post("login")
  @Public()
  @UseGuards(LocalAuthGuard)
  async login(@Body() reqLoginDto: ReqLoginDto, @Req() req: Request): Promise<ResLoginDto> {
    return await this.loginService.login(req);
  }

  @Public()
  @Post("logout")
  async logout(@Headers("Authorization") authorization: string) {
    if (authorization) {
      const token = authorization.slice(7);
      await this.loginService.logout(token);
    }
  }

  /* 获取用户信息 */
  @Get("getInfo")
  async getInfo(@User(UserEnum.userId) userId: number) {
    const info = await this.loginService.getInfo(userId);
    return DataObj.create(info);
  }

  /** 获取用户路由信息 */
  @Get("getRouters")
  async getRouters(@User(UserEnum.userId) userId: number) {
    const router = await this.loginService.getRouterByUser(userId);
    return DataObj.create(router);
  }
}
